var express = require('express');
var router = express.Router();
var _ = require("underscore");

var GenerateCodeUtil = require('../lib/utils/GenerateCode');
var SecurityUtil = require('../lib/utils/SecurityUtil');
var mysql = require("mysql");
var connection = require('../lib/utils/DbconnectUtil');

router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

/**
 * 注册新用户
 */
router.post('/', function (req, res, next) {
    console.log('register.......');

    console.log(req.body);
    var salt = GenerateCodeUtil.genSaltValue();
    var newUser = {
        password: SecurityUtil.genPasswordCipherText(req.body.password, salt),
        salt: salt,
        nick_name: req.body.nickName | req.body.email,
        user_name: req.body.email,
        email:req.body.email,
        phone_number: req.body.phoneNumber
    };

    //判断是否存在
 //   console.log("email: "+req.body.email+' phoneNumber'+req.body.phoneNumber);

    connection().query('select * from t_user where email = ? or phone_number = ?',[req.body.email,req.body.phoneNumber],function(err,result){
        if (err) {
            console.log('error: %s', 'register error.');
            console.error(err);
            res.send(500, '注册失败');
            return;
        }
        if(result && result.length > 0){
            _.each(result,function(element){
                if(req.body.email == element.email){
                    res.send({
                        result:false,
                        message:"邮箱已被注册"
                    });
                    return ;
                }
                else if(req.body.phoneNumber == element.phone_number){
                    res.send({
                        result:false,
                        message:"手机号已被注册"
                    });
                    return ;
                }

            });
        }
        else{
            connection().query('INSERT INTO t_user SET ?', newUser, function (err, result) {
                console.log('after call db.....');
                if (err) {
                    console.log('error: %s', 'register error.');
                    console.error(err);
                    res.send(500, '注册失败');
                    return;
                }
                res.send({
                    result: true,
                    user: {
                        userId : result.id,
                        nickName: result.nick_name,
                        email:req.body.email,
                        phoneNumber: result.phone_number,
                        userName:result.user_name
                        }
                });
            });
        }

    });
});


/**
 * 登录
 */
router.post('/login/', function (req, res, next) {
    console.log('login.......');

    if (!req.body.password || (!req.body.email && !req.body.phoneNumber)) {
        res.send({
            result: false,
            message: '用户或密码不正确'
        });
        return ;
    };

    var params = [];
    var queryStr ='';

    if(req.body.email){
        queryStr = 'select * from t_user where email = ? ';
        params.push(req.body.email);
    }
    else if(req.body.phoneNumber){
        queryStr = 'select * from t_user where phone_number = ? ';
        params.push(req.body.phoneNumber);
    }
    else {
        res.send({
            result: false,
            message: '用户或密码不正确'
        });
        return;
    }

    connection().query(queryStr, params, function (err, results) {
        if (err) {
            console.log(err);
            res.send({
                result: false,
                message: '服务器内部异常'
            });
        } else if (results && results[0]) {
            var chipher = SecurityUtil.genPasswordCipherText(req.body.password, results[0].salt);
            if (chipher === results[0].password) {
                var jwtToken = SecurityUtil.getJwtSign(results[0]);
                res.cookie('jwtToken', jwtToken, {maxAge: 7200000, path: '/'});
                res.send({
                    result: true,
                    user: {
                        id: results[0].id,
                        nickName: results[0].nick_name,
                        userName: results[0].user_name,
                        phoneNumber:results[0].phone_number,
                        email:results[0].email
                    }
                });
            } else {
                res.send({
                    result: false,
                    message: '用户或密码不正确'
                });
            }
        }
        else {
            res.send({
                result: false,
                message: '当前用户不存在'
            });
        }
    });

    /**
     * 退出登录
     */
    router.post('/logout/', function (req, res, next) {
        res.clearCookie('jwtToken', { path: '/' });
        res.send({
            result: true,
            message: '已经退出登录'
        });
    });
});

module.exports = router;
